#!/bin/sh

ROOT_DIR=$PWD
OUTPUT_DIR_Perf=$PWD/perf
OUTPUT_DIR_Test=$PWD/test
mkdir -p "$OUTPUT_DIR_Perf"
mkdir -p "$OUTPUT_DIR_Test"
COUNT=0
count_file=$(mktemp)  # 创建临时文件来存储计数器

# 查找所有 Rust 文件中的测试项
TOTAL=$(find "$ROOT_DIR" -name '*.rs' -exec grep -oP 'fn\s+\K(test\w*)' {} +)
#echo "Found the following test functions: $TOTAL"
TOTAL_COUNT=$(echo "$TOTAL" | wc -l)
echo "Total number of test functions: $TOTAL_COUNT"

# 查找所有 .rs 文件
find  -name '*.rs' | while read -r test_file; do
    echo "Processing file: $test_file"
    cd $(dirname "$test_file")
    grep -oP 'fn\s+\K(test\w*)' "./$(echo "$test_file" | sed 's:.*/::')" | while read -r test_func; do
        echo "Found test function: $test_func"
        # 生成执行命令
        cmd="cargo test $test_func"
        path=$(echo "$test_file" | sed -n 's|.*\./\(.*\)\..*|\1|p' | sed 's|/|#|g')
        file="$test_func#$path"

        if [ -f "$OUTPUT_DIR_Test/$file.txt" ]; then
            echo "Test result file already exists: $OUTPUT_DIR_Test/$file.txt"
        else
            $cmd > $file.txt 2>&1
            echo $test_func >>$file.txt
            echo "($test_file)" >>$file.txt
            mv $file.txt $OUTPUT_DIR_Test
        fi
        
        # 调用 perf 脚本
        if [ -f "$OUTPUT_DIR_Perf/$file.txt" ]; then
            echo "The perf test has completed"
        else
            $ROOT_DIR/performance_counter_920.sh "$cmd" "$OUTPUT_DIR_Perf" "$test_file"
        fi
        
        # 更新计数器
        COUNT=$((COUNT + 1))
        echo $COUNT > "$count_file"
        echo "Rate of progress: $COUNT/$TOTAL_COUNT"
        echo ""
    done
    cd $ROOT_DIR
    COUNT=$(cat "$count_file")
done

COUNT=$(cat "$count_file")
rm "$count_file"
echo "Test completed in $(($SECONDS / 3600)) hours $((($SECONDS % 3600) / 60)) minutes $(($SECONDS % 60)) seconds."
echo "Total number of tests completed: $COUNT"

